
<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

//  for nginx
function my_fastcgi_finish_request(){
	if( function_exists( 'fastcgi_finish_request' ) ){
		fastcgi_finish_request();
	} else {
		set_time_limit(600);
		flush();
		ob_flush();
	}
}

function getUrlAction($url)
{
	if(!$url)
		return '';
	$url = str_replace(array('http://', 'https://'), '', $url); 
	$url = explode('?', $url);
	$url = explode('/', $url[0]);
	return isset($url[2]) ? $url[2] : '';

}

function build_url($service = '', $params = array())
{
	$url = JAVA_SERVICE . "{$service}?";
	if($params) {
		if(is_array($params)) {
			foreach ($params as $key => $value) {
				$url = $url . "{$key}=" . (is_array($value) ? implode(',', $value) : $value) . '&';
			}
		} else {
			$url = $url . $params . '&';
		}
	}

	return $url . 'token=' . JAVA_SERVICE_TOKEN;
}

function display_date($time) {
	if((int) $time <= 0)
		return '';
	return date('Y-m-d H:i:s', $time);
}

function in_ip($localIp,$ipRanges) {
	$localIp = ip2long($localIp);
	foreach($ipRanges as $val) {
		if($localIp >= ip2long($val[0]) && $localIp <= ip2long($val[1])) {
			return true;
		}
	}
	return false;
} 
        

/*清除一个数组中item中存在的垃圾值*/
function junky_words_cleaner(&$arr){
	foreach( $arr as $key => &$value){	
		if( is_array($value) ){
			junky_words_cleaner($value);
		}else{
			if( is_junky_word($value) ){
				unset($arr[$key]);
			} 
		}
	}
}
/** 测试是否是一些没有用的垃圾词语，如纯符号，纯数字等 **/
function is_junky_word($word){
   //return preg_match("/[\d+\W+_a-z]/iu", $word);
   return  preg_match('/[$-/\:-?{-~!"^_`\[\]]/iu', $word) || mb_strlen( $word , 'UTF-8') < 2;
}


/**
 * 防止修改key的array_merge
 */
function array_merge_keys(){
	$args = func_get_args();
	$result = array();
	foreach ($args as &$array) {
		foreach ($array as $key=>&$value) {
			$result[$key] = $value;
		}
	}
	return $result;
}

/**
 * 防止修改keyd
 */
function array_merge_recursive_unique()
{
	$args = func_get_args();
	$array = $args[0];
	if (!is_array($array))
	{
		return $array;
	}
	
	for ($i = 1; $i < count($args); $i++)
	{
		if (is_array($args[$i]))
		{
		    $array1 = $args[$i];
        	//简化版
        	foreach( $array1 as $key => $value){
       	    
                if( isset($array[$key]) && is_array( $array[$key] )){
                    $value = array_merge_recursive_unique($array[$key] , $value); 
                }
        	    
                if( !isset($array[$key]) || is_array($value) ){
                    $array[$key] = $value;
                }else{
                    if( !in_array($value , $array , true) ){
                        $array[] = $value;
                    }
                }
                
        	}
		}
	}
	return $array;
}
/**
 * 递归array_values方法获得多维数组的值,去掉keys
 */
function array_values_recursive($ary)
{
   $lst = array();
   foreach( array_keys($ary) as $k ){
      $v = $ary[$k];
      if (is_scalar($v)) {
         $lst[] = $v;
      } elseif (is_array($v)) {
         $lst = array_merge( $lst,
            array_values_recursive($v)
         );
      }
   }
   return $lst;
}

/**
 * format the value of null display in the table
 * @param string ,  $str
 * @return string , $return
 * 
 */
function display_str( $str , $holder = '--'){
    return $str ? $str : $holder;
}

function price_display_str($value='')
{
	return ((int)($value * 100)) / 100;
}

/**
 * 显示百分比数据
 */
function display_ratio( $str , $holder = '--'){
	return $str ? round($str * 100) : $holder;
}

/** change a price from yuan to cent */
function getPriceofCent($value , $is_cent=false){
    //replace the rmy symbol if it has
    $value = str_replace( "￥" , "" ,$value);
    $value = floatval($value);
    $value = $is_cent ? $value : $value * 100;
    return $value;
}
/** get a big random int */
function getBigRandomNumber($min, $max) {
  $difference   = bcadd(bcsub($max,$min),1);
  $rand_percent = bcdiv(mt_rand(), mt_getrandmax(), 8); // 0 - 1.0
  return bcadd($min, bcmul($difference, $rand_percent, 8), 0);
}

/**
 * 检查第一个数组的值在第二个数组中是否有更新, 如果有更新, 返回更新的键和值, 否则返回空数组.
 *  2个数组都最好是键值对, 如果是自然数为键值, 则一般两个数组的个数和值类型相对一致才有意义.
 *  
 * @param array(k=>v) $a1 第一个数组, 基数组.
 * @param array(k=>v) $a2 第二个数组, 新数组.
 * @return array(k=>v) 有差别的值.
 */
function array_kv_diff($a1, $a2) {
	$diff = array();
	foreach($a1 as $k => $v1) {
		if(isset($a2[$k]) && $v1 != $a2[$k]) {
			$diff[$k] = $a2[$k];
		}
	}	
	return $diff;
}

/**
 *  get api eorro 
 */
function getTopError($msg){
    $msgObject = json_decode($msg, true);
    if ( isset($msgObject["error_response"]["sub_msg"]) ){
        return $msgObject["error_response"]["sub_msg"];
    } else if(isset($msgObject["error_response"]["msg"])) {
    	return $msgObject["error_response"]["msg"];
    } else{
        return $msg;
    }
}
function getTopErrorCode($msg){
	$msgObject = json_decode($msg,true);
	if ( isset($msgObject["error_response"]["code"]) ){
		return $msgObject["error_response"]["code"];
	}else{
		return -1;
	}
}
function getTopErrorSubCode($msg){
	$msgObject = json_decode($msg,true);
	if ( isset($msgObject["error_response"]["sub_code"]) ){
		return $msgObject["error_response"]["sub_code"];
	}else{
		return '';
	}
}

/** get micro secs */
function getmicrotime(){ 
    list($usec, $sec) = explode(" ",microtime()); 
    return ((float)$usec + (float)$sec); 
} 
/** get the access token of a user
 * param int, user id
 * return string ,acces token
 */
function getUserAccessToken($user_id, $sess = true){
	if($sess){
	    $user_info = session("me");
	    $oauth = $user_info["oauth"];	
	    return $oauth["access_token"];
	} else {
		return null;
	}
}

/** 
 * convert objects to associate array 
 */
function object_to_array($data){
    if (is_array($data) || is_object($data))
    {
        $result = array();
        foreach ($data as $key => $value)
        {
            $result[$key] = object_to_array($value);
        }
        return $result;
    }
    return $data;
}

 /**
  * if a url is true a url.
  *
  * TODO This function has problems!!!
  *
  * @param $url the url address
  * @return bool true if it is , otherwise false.
  *
  */
function is_url($url){
	$reg = '/^https?:\/\/[A-Za-z0-9\.]+[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/';
	return preg_match($reg, $url)===1;
}


/**
 * get how many hours before
 * @param int time stamp
 * @return String 
 */
function format_date($dateline){
	//$hours = ceil( ( time() - $dateline) / 3600 );

	//$val->news->news_dateline
	
	$dataline = getdate($dateline);	
	$time = getdate();

	$sub = (int)(($time[0] - $dataline[0])/86400);
	$format = '';
	switch((string)$sub){
		case '0':
			$format = "今天  " .$dataline['hours'].':'.$dataline['minutes'] ;
			break;
		case '1':
			$format = "昨天  " .$dataline['hours'].':'.$dataline['minutes'] ;
			break;	
		case '2':
			$format = "前天  " .$dataline['hours'].':'.$dataline['minutes'] ;
			break;	
		default:
			$format = $dataline['mon'].'-' . $dataline['mday'] .' '.$dataline['hours'].':'.$dataline['minutes'] ;
			break;	
	}
	

	return $format;
}
	
/**
 * 返回给定日期的早上0时的时刻的unix_timestamp.
 * @param int $shiftDays = 0. 0表示今天早上0时. +N天表示从今天开始的未来N天的0时. -N表示往前N天的早上0时.
 * @return int
 */
function date2time($shiftDays = 0) {
	return strtotime(date('Y-m-d')) + $shiftDays * 86400;
}

/**
 * Make a union of 2 arrays on their VALUES! Compared to this, the operator '+' works on the keys.
 * 
 * @param array $a1
 * @param array $a2
 * @return array
 */
function array_union($a1, $a2) {
	return array_unique(array_merge($a1, $a2));
}

/**
 * Extract a column from an array/object.
 * 
 * @param array $arr	A 2D array or an array of objects.
 * @param string $col	Name of the column to extract.
 * @param bool $isEleObj 数据元素是否为对象. 
 * @param bool $isNewKey 是否重置数组的key为0, 1, 2, ...
 * @return array If the given array is empty. array() is returned.
 */
if(!function_exists('array_column')) {
	function array_column($arr, $col, $isEleObj = false, $resetKey = false) {
		if(!$arr)
			return array();
		
		$colArr = array();
		if(!$isEleObj) {
			if(!$resetKey) {
				foreach ($arr as $k => $v) {
					$colArr[$k] = $v[$col];
				}
			} else {
				foreach ($arr as $k => $v) {
					$colArr[] = $v[$col];
				}
			}
		} else {
			if(!$resetKey) {
				foreach ($arr as $k => $v) {
					$colArr[$k] = $v->$col;
				}
			} else {
				foreach ($arr as $k => $v) {
					$colArr[] = $v->$col;
				}
			}
		}
		return $colArr;
	}
}

/**
 * 计算一个数值数组的平均值
 * @param array(number) $a
 * @return false|number
 */
function array_avg($a) {
	if(!$a) 
		return false;
	else 
		return array_sum($a) / count($a);
}

/**
 * glue a 2D-array.
 * 
 * For example: join_2d(',', '_', array(array(1,2), array(3,4))) returns '1_2,3_4'.
 * 
 * @param string $glue1 The outer glue
 * @param string $glue2 The inner glue.
 * @param array(2D) $a The array to glue.
 * @return string The glued array in string. return empty string '' if empty array given.
 */
function join_2d($glue1, $glue2, $a) {
	if(!$a)
		return '';
	$a2 = array();
	foreach($a as $ele) {
		$a2[] = join($glue2, $ele);
	}
	return join($glue1, $a2);
}

/**
 * 保证一个数组里面是否都是整型数字. 非数字的替换为0.
 * 
 * @param array(number) $arr
 * @param bool $isBigInt 要检查的数字是否是大整型, 比如keyord_id, product_id之类的超过php整型范围的数字.
 * @return 检查过的数组.
 */
function check_int_arr($arr, $isBigInt = false) {
	if($arr === null)
		return null;
	$checkedArr = array();
	if(!$isBigInt) {
		foreach($arr as $v) {
			$checkedArr[] = intval($v);
		}
	} else {
		foreach($arr as $v) {
			$v = preg_replace( '/[^0-9]/', '', $v);
			$checkedArr[] = $v ? $v : 0;
		}
	}
	return $checkedArr;
}


function uc_cmp_hprice($a, $b){
    if( $a[0] == $b[0] ) return 0;
    return $a[0] > $b[0] ? 1 : -1;
}
/** 一系列自定义排序方法。用来给关键词按不同结果排序。*/
function uc_cmp_pv_asc($a, $b) {
	if ($a['pv'] == $b['pv']) return 0;
	return ($a['pv'] > $b['pv']) ? 1 : -1;
}
function uc_cmp_click_asc($a, $b) {
	if ($a['click'] == $b['click']) return 0;
	return ($a['click'] > $b['click']) ? 1 : -1;
}
function uc_cmp_avg_price_asc($a, $b) {
	if ($a['avg_price'] == $b['avg_price']) return 0;
	return ($a['avg_price'] > $b['avg_price']) ? 1 : -1;
}
function uc_cmp_competition_asc($a, $b) {
	if ($a['competition'] == $b['competition']) return 0;
	return ($a['competition'] > $b['competition']) ? 1 : -1;
}
function uc_cmp_ctr_asc($a, $b) {
	if ($a['ctr'] == $b['ctr']) return 0;
	return ($a['ctr'] > $b['ctr']) ? 1 : -1;
}
function uc_cmp_pv_dec($a, $b) {
	if ($a['pv'] == $b['pv']) return 0;
	return ($a['pv'] < $b['pv']) ? 1 : -1;
}
function uc_cmp_click_dec($a, $b) {
	if ($a['click'] == $b['click']) return 0;
	return ($a['click'] < $b['click']) ? 1 : -1;
}
function uc_cmp_avg_price_dec($a, $b) {
	if ($a['avg_price'] == $b['avg_price']) return 0;
	return ($a['avg_price'] < $b['avg_price']) ? 1 : -1;
}
function uc_cmp_competition_dec($a, $b) {
	if ($a['competition'] == $b['competition']) return 0;
	return ($a['competition'] < $b['competition']) ? 1 : -1;
}
function uc_cmp_ctr_dec($a, $b) {
	if ($a['ctr'] == $b['ctr']) return 0;
	return ($a['ctr'] < $b['ctr']) ? 1 : -1;
}

// for keyword sort.
function uc_cmp_impressions_dec($a, $b) {
	if ($a['impressions'] == $b['impressions']) return 0;
	return ($a['impressions'] < $b['impressions']) ? 1 : -1;
}
function uc_cmp_impressions_asc($a, $b) {
	if ($a['impressions'] == $b['impressions']) return 0;
	return ($a['impressions'] > $b['impressions']) ? 1 : -1;
}
function uc_cmp_cost_dec($a, $b) {
	if ($a['cost'] == $b['cost']) return 0;
	return ($a['cost'] < $b['cost']) ? 1 : -1;
}
function uc_cmp_cost_asc($a, $b) {
	if ($a['cost'] == $b['cost']) return 0;
	return ($a['cost'] > $b['cost']) ? 1 : -1;
}
function uc_cmp_cpc_dec($a, $b) {
	if ($a['cpc'] == $b['cpc']) return 0;
	return ($a['cpc'] < $b['cpc']) ? 1 : -1;
}
function uc_cmp_cpc_asc($a, $b) {
	if ($a['cpc'] == $b['cpc']) return 0;
	return ($a['cpc'] > $b['cpc']) ? 1 : -1;
}
function uc_cmp_roi_dec($a, $b) {
	if ($a['roi'] == $b['roi']) return 0;
	return ($a['roi'] < $b['roi']) ? 1 : -1;
}
function uc_cmp_roi_asc($a, $b) {
	if ($a['roi'] == $b['roi']) return 0;
	return ($a['roi'] > $b['roi']) ? 1 : -1;
}
function uc_cmp_cpm_dec($a, $b) {
	if ($a['cpm'] == $b['cpm']) return 0;
	return ($a['cpm'] < $b['cpm']) ? 1 : -1;
}
function uc_cmp_cpm_asc($a, $b) {
	if ($a['cpm'] == $b['cpm']) return 0;
	return ($a['cpm'] > $b['cpm']) ? 1 : -1;
}
function uc_cmp_direct_pay_dec($a, $b) {
	if ($a['direct_pay'] == $b['direct_pay']) return 0;
	return ($a['direct_pay'] < $b['direct_pay']) ? 1 : -1;
}
function uc_cmp_direct_pay_asc($a, $b) {
	if ($a['direct_pay'] == $b['direct_pay']) return 0;
	return ($a['direct_pay'] > $b['direct_pay']) ? 1 : -1;
}
function uc_cmp_indirect_pay_dec($a, $b) {
	if ($a['indirect_pay'] == $b['indirect_pay']) return 0;
	return ($a['indirect_pay'] < $b['indirect_pay']) ? 1 : -1;
}
function uc_cmp_indirect_pay_asc($a, $b) {
	if ($a['indirect_pay'] == $b['indirect_pay']) return 0;
	return ($a['indirect_pay'] > $b['indirect_pay']) ? 1 : -1;
}
function uc_cmp_sales_dec($a, $b) {
	if ($a['sales'] == $b['sales']) return 0;
	return ($a['sales'] < $b['sales']) ? 1 : -1;
}
function uc_cmp_sales_asc($a, $b) {
	if ($a['sales'] == $b['sales']) return 0;
	return ($a['sales'] > $b['sales']) ? 1 : -1;
}
function uc_cmp_direct_pay_count_dec($a, $b) {
	if ($a['direct_pay_count'] == $b['direct_pay_count']) return 0;
	return ($a['direct_pay_count'] < $b['direct_pay_count']) ? 1 : -1;
}
function uc_cmp_direct_pay_count_asc($a, $b) {
	if ($a['direct_pay_count'] == $b['direct_pay_count']) return 0;
	return ($a['direct_pay_count'] > $b['direct_pay_count']) ? 1 : -1;
}
function uc_cmp_indirect_pay_count_dec($a, $b) {
	if ($a['indirect_pay_count'] == $b['indirect_pay_count']) return 0;
	return ($a['indirect_pay_count'] < $b['indirect_pay_count']) ? 1 : -1;
}
function uc_cmp_indirect_pay_count_asc($a, $b) {
	if ($a['indirect_pay_count'] == $b['indirect_pay_count']) return 0;
	return ($a['indirect_pay_count'] > $b['indirect_pay_count']) ? 1 : -1;
}
function uc_cmp_total_pay_count_dec($a, $b) {
	if ($a['total_pay_count'] == $b['total_pay_count']) return 0;
	return ($a['total_pay_count'] < $b['total_pay_count']) ? 1 : -1;
}
function uc_cmp_total_pay_count_asc($a, $b) {
	if ($a['total_pay_count'] == $b['total_pay_count']) return 0;
	return ($a['total_pay_count'] > $b['total_pay_count']) ? 1 : -1;
}
function uc_cmp_fav_shop_count_dec($a, $b) {
	if ($a['fav_shop_count'] == $b['fav_shop_count']) return 0;
	return ($a['fav_shop_count'] < $b['fav_shop_count']) ? 1 : -1;
}
function uc_cmp_fav_shop_count_asc($a, $b) {
	if ($a['fav_shop_count'] == $b['fav_shop_count']) return 0;
	return ($a['fav_shop_count'] > $b['fav_shop_count']) ? 1 : -1;
}
function uc_cmp_fav_item_count_dec($a, $b) {
	if ($a['fav_item_count'] == $b['fav_item_count']) return 0;
	return ($a['fav_item_count'] < $b['fav_item_count']) ? 1 : -1;
}
function uc_cmp_fav_item_count_asc($a, $b) {
	if ($a['fav_item_count'] == $b['fav_item_count']) return 0;
	return ($a['fav_item_count'] > $b['fav_item_count']) ? 1 : -1;
}
function uc_cmp_avgpos_dec($a, $b) {
	if ($a['avgpos'] == $b['avgpos']) return 0;
	return ($a['avgpos'] < $b['avgpos']) ? 1 : -1;
}
function uc_cmp_avgpos_asc($a, $b) {
	if ($a['avgpos'] == $b['avgpos']) return 0;
	return ($a['avgpos'] > $b['avgpos']) ? 1 : -1;
}
function uc_cmp_keywordstr_dec($a, $b) {
	if ($a['keywordstr'] == $b['keywordstr']) return 0;
	return ($a['keywordstr'] < $b['keywordstr']) ? 1 : -1;
}
function uc_cmp_keywordstr_asc($a, $b) {
	if ($a['keywordstr'] == $b['keywordstr']) return 0;
	return ($a['keywordstr'] > $b['keywordstr']) ? 1 : -1;
}
function uc_cmp_qscore_dec($a, $b) {
	if ($a['qscore'] == $b['qscore']) return 0;
	return ($a['qscore'] < $b['qscore']) ? 1 : -1;
}
function uc_cmp_qscore_asc($a, $b) {
	if ($a['qscore'] == $b['qscore']) return 0;
	return ($a['qscore'] > $b['qscore']) ? 1 : -1;
}
function uc_cmp_wireless_qscore_dec($a, $b) {
	if ($a['wireless_qscore'] == $b['wireless_qscore']) return 0;
	return ($a['wireless_qscore'] < $b['wireless_qscore']) ? 1 : -1;
}
function uc_cmp_wireless_qscore_asc($a, $b) {
	if ($a['wireless_qscore'] == $b['wireless_qscore']) return 0;
	return ($a['wireless_qscore'] > $b['wireless_qscore']) ? 1 : -1;
}
function uc_cmp_cart_total_dec($a, $b) {
	if ($a['cart_total'] == $b['cart_total']) return 0;
	return ($a['cart_total'] < $b['cart_total']) ? 1 : -1;
}
function uc_cmp_cart_total_asc($a, $b) {
	if ($a['cart_total'] == $b['cart_total']) return 0;
	return ($a['cart_total'] > $b['cart_total']) ? 1 : -1;
}

function uc_cmp_log_desc($a, $b) {
	if ($a['updated_stp'] == $b['updated_stp']) return 0;
	return ($a['updated_stp'] < $b['updated_stp']) ? 1 : -1;
}
// 全网数据 --- impressions ----
function uc_cmp_q_impressions_desc($a, $b) {
	if ($a['q_impressions'] == $b['q_impressions']) return 0;
	return ($a['q_impressions'] < $b['q_impressions']) ? 1 : -1;
}
function uc_cmp_q_impressions_asc($a, $b) {
	if ($a['q_impressions'] == $b['q_impressions']) return 0;
	return ($a['q_impressions'] > $b['q_impressions']) ? 1 : -1;
}
// 全网数据 --- 平均点击花费 ----
function uc_cmp_q_cpc_desc($a, $b) {
	if ($a['q_cpc'] == $b['q_cpc']) return 0;
	return ($a['q_cpc'] < $b['q_cpc']) ? 1 : -1;
}
function uc_cmp_q_cpc_asc($a, $b) {
	if ($a['q_cpc'] == $b['q_cpc']) return 0;
	return ($a['q_cpc'] > $b['q_cpc']) ? 1 : -1;
}
// 全网数据 --- 投入产出比 ----
function uc_cmp_q_roi_desc($a, $b) {
	if ($a['q_roi'] == $b['q_roi']) return 0;
	return ($a['q_roi'] < $b['q_roi']) ? 1 : -1;
}
function uc_cmp_q_roi_asc($a, $b) {
	if ($a['q_roi'] == $b['q_roi']) return 0;
	return ($a['q_roi'] > $b['q_roi']) ? 1 : -1;
}
// 全网数据 --- 点击转化率 ----
function uc_cmp_q_cvr_desc($a, $b) {
	if ($a['q_cvr'] == $b['q_cvr']) return 0;
	return ($a['q_cvr'] < $b['q_cvr']) ? 1 : -1;
}
function uc_cmp_q_cvr_asc($a, $b) {
	if ($a['q_cvr'] == $b['q_cvr']) return 0;
	return ($a['q_cvr'] > $b['q_cvr']) ? 1 : -1;
}
// 全网数据 --- 竞争度 ----
function uc_cmp_q_competition_desc($a, $b) {
	if ($a['q_competition'] == $b['q_competition']) return 0;
	return ($a['q_competition'] < $b['q_competition']) ? 1 : -1;
}
function uc_cmp_q_competition_asc($a, $b) {
	if ($a['q_competition'] == $b['q_competition']) return 0;
	return ($a['q_competition'] > $b['q_competition']) ? 1 : -1;
}

// 后台错误 --- 推广计划 ---
function uc_cmp_campaign_asc($a, $b)
{
	if ($a['campaign_num'] == $b['campaign_num']) return 0;
	return ($a['campaign_num'] > $b['campaign_num']) ? 1 : -1;
}
function uc_cmp_campaign_desc($a, $b)
{
	if ($a['campaign_num'] == $b['campaign_num']) return 0;
	return ($a['campaign_num'] < $b['campaign_num']) ? 1 : -1;
}

// 后台错误 --- 推广组 ---
function uc_cmp_adgroup_asc($a, $b)
{
	if ($a['adgroup_num'] == $b['adgroup_num']) return 0;
	return ($a['adgroup_num'] > $b['adgroup_num']) ? 1 : -1;
}
function uc_cmp_adgroup_desc($a, $b)
{
	if ($a['adgroup_num'] == $b['adgroup_num']) return 0;
	return ($a['adgroup_num'] < $b['adgroup_num']) ? 1 : -1;
}

function uc_cmp_keyword_asc($a, $b)
{
	if ($a['keyword_num'] == $b['keyword_num']) return 0;
	return ($a['keyword_num'] > $b['keyword_num']) ? 1 : -1;
}
function uc_cmp_keyword_desc($a, $b)
{
	if ($a['keyword_num'] == $b['keyword_num']) return 0;
	return ($a['keyword_num'] < $b['keyword_num']) ? 1 : -1;
}

function uc_cmp_creative_asc($a, $b)
{
	if ($a['creative_num'] == $b['creative_num']) return 0;
	return ($a['creative_num'] > $b['creative_num']) ? 1 : -1;
}
function uc_cmp_creative_desc($a, $b)
{
	if ($a['creative_num'] == $b['creative_num']) return 0;
	return ($a['creative_num'] < $b['creative_num']) ? 1 : -1;
}

function uc_cmp_recommends_asc($a, $b)
{
	if ($a['recommends_num'] == $b['recommends_num']) return 0;
	return ($a['recommends_num'] > $b['recommends_num']) ? 1 : -1;
}
function uc_cmp_recommends_desc($a, $b)
{
	if ($a['recommends_num'] == $b['recommends_num']) return 0;
	return ($a['recommends_num'] < $b['recommends_num']) ? 1 : -1;
}

function uc_cmp_insightdata_asc($a, $b)
{
	if ($a['insightdata_num'] == $b['insightdata_num']) return 0;
	return ($a['insightdata_num'] > $b['insightdata_num']) ? 1 : -1;
}
function uc_cmp_insightdata_desc($a, $b)
{
	if ($a['insightdata_num'] == $b['insightdata_num']) return 0;
	return ($a['insightdata_num'] < $b['insightdata_num']) ? 1 : -1;
}

// 后台推广管理 ---  ---
function uc_cmp_sem_use_num_asc($a, $b)
{
	if ($a['sem_use_num'] == $b['sem_use_num']) return 0;
	return ($a['sem_use_num'] > $b['sem_use_num']) ? 1 : -1;
}
function uc_cmp_sem_use_num_desc($a, $b)
{
	if ($a['sem_use_num'] == $b['sem_use_num']) return 0;
	return ($a['sem_use_num'] < $b['sem_use_num']) ? 1 : -1;
}

function uc_cmp_sem_total_num_asc($a, $b)
{
	if ($a['sem_total_num'] == $b['sem_total_num']) return 0;
	return ($a['sem_total_num'] > $b['sem_total_num']) ? 1 : -1;
}
function uc_cmp_sem_total_num_desc($a, $b)
{
	if ($a['sem_total_num'] == $b['sem_total_num']) return 0;
	return ($a['sem_total_num'] < $b['sem_total_num']) ? 1 : -1;
}

function uc_cmp_sem_custom_num_asc($a, $b)
{
	if ($a['sem_custom_num'] == $b['sem_custom_num']) return 0;
	return ($a['sem_custom_num'] > $b['sem_custom_num']) ? 1 : -1;
}
function uc_cmp_sem_custom_num_desc($a, $b)
{
	if ($a['sem_custom_num'] == $b['sem_custom_num']) return 0;
	return ($a['sem_custom_num'] < $b['sem_custom_num']) ? 1 : -1;
}

function uc_cmp_sem_public_num_asc($a, $b)
{
	if ($a['sem_public_num'] == $b['sem_public_num']) return 0;
	return ($a['sem_public_num'] > $b['sem_public_num']) ? 1 : -1;
}
function uc_cmp_sem_public_num_desc($a, $b)
{
	if ($a['sem_public_num'] == $b['sem_public_num']) return 0;
	return ($a['sem_public_num'] < $b['sem_public_num']) ? 1 : -1;
}

function uc_cmp_kawei_total_num_asc($a, $b)
{
	if ($a['kawei_total_num'] == $b['kawei_total_num']) return 0;
	return ($a['kawei_total_num'] > $b['kawei_total_num']) ? 1 : -1;
}
function uc_cmp_kawei_total_num_desc($a, $b)
{
	if ($a['kawei_total_num'] == $b['kawei_total_num']) return 0;
	return ($a['kawei_total_num'] < $b['kawei_total_num']) ? 1 : -1;
}

function uc_cmp_kawei_use_num_asc($a, $b)
{
	if ($a['kawei_use_num'] == $b['kawei_use_num']) return 0;
	return ($a['kawei_use_num'] > $b['kawei_use_num']) ? 1 : -1;
}
function uc_cmp_kawei_use_num_desc($a, $b)
{
	if ($a['kawei_use_num'] == $b['kawei_use_num']) return 0;
	return ($a['kawei_use_num'] < $b['kawei_use_num']) ? 1 : -1;
}

function uc_cmp_cam_num_asc($a, $b)
{
	if ($a['cam_num'] == $b['cam_num']) return 0;
	return ($a['cam_num'] > $b['cam_num']) ? 1 : -1;
}
function uc_cmp_cam_num_desc($a, $b)
{
	if ($a['cam_num'] == $b['cam_num']) return 0;
	return ($a['cam_num'] < $b['cam_num']) ? 1 : -1;
}

function uc_cmp_auto_cam_num_asc($a, $b)
{
	if ($a['auto_cam_num'] == $b['auto_cam_num']) return 0;
	return ($a['auto_cam_num'] > $b['auto_cam_num']) ? 1 : -1;
}
function uc_cmp_auto_cam_num_desc($a, $b)
{
	if ($a['auto_cam_num'] == $b['auto_cam_num']) return 0;
	return ($a['auto_cam_num'] < $b['auto_cam_num']) ? 1 : -1;
}

function uc_cmp_wireless_cam_num_asc($a, $b)
{
	if ($a['wireless_cam_num'] == $b['wireless_cam_num']) return 0;
	return ($a['wireless_cam_num'] > $b['wireless_cam_num']) ? 1 : -1;
}
function uc_cmp_wireless_cam_num_desc($a, $b)
{
	if ($a['wireless_cam_num'] == $b['wireless_cam_num']) return 0;
	return ($a['wireless_cam_num'] < $b['wireless_cam_num']) ? 1 : -1;
}

// 后台推广管理 ---  ---
function uc_cmp_userProfitList_like_pay_asc($a, $b)
{
	if ($a['like_pay'] == $b['like_pay']) return 0;
	return ($a['like_pay'] > $b['like_pay']) ? 1 : -1;
}
function uc_cmp_userProfitList_like_pay_desc($a, $b)
{
	if ($a['like_pay'] == $b['like_pay']) return 0;
	return ($a['like_pay'] < $b['like_pay']) ? 1 : -1;
}

function uc_cmp_userProfitList_like_cost_asc($a, $b)
{
	if ($a['like_cost'] == $b['like_cost']) return 0;
	return ($a['like_cost'] > $b['like_cost']) ? 1 : -1;
}
function uc_cmp_userProfitList_like_cost_desc($a, $b)
{
	if ($a['like_cost'] == $b['like_cost']) return 0;
	return ($a['like_cost'] < $b['like_cost']) ? 1 : -1;
}

function uc_cmp_userProfitList_like_roi_asc($a, $b)
{
	if ($a['like_roi'] == $b['like_roi']) return 0;
	return ($a['like_roi'] > $b['like_roi']) ? 1 : -1;
}
function uc_cmp_userProfitList_like_roi_desc($a, $b)
{
	if ($a['like_roi'] == $b['like_roi']) return 0;
	return ($a['like_roi'] < $b['like_roi']) ? 1 : -1;
}

function uc_cmp_userProfitList_nick_asc($a, $b)
{
	if ($a['nick'] == $b['nick']) return 0;
	return ($a['nick'] > $b['nick']) ? 1 : -1;
}
function uc_cmp_userProfitList_nick_desc($a, $b)
{
	if ($a['nick'] == $b['nick']) return 0;
	return ($a['nick'] < $b['nick']) ? 1 : -1;
}

function uc_cmp_userProfitList_click_asc($a, $b)
{
	if ($a['click'] == $b['click']) return 0;
	return ($a['click'] > $b['click']) ? 1 : -1;
}
function uc_cmp_userProfitList_click_desc($a, $b)
{
	if ($a['click'] == $b['click']) return 0;
	return ($a['click'] < $b['click']) ? 1 : -1;
}

function uc_cmp_userProfitList_cpc_asc($a, $b)
{
	if ($a['cpc'] == $b['cpc']) return 0;
	return ($a['cpc'] > $b['cpc']) ? 1 : -1;
}
function uc_cmp_userProfitList_cpc_desc($a, $b)
{
	if ($a['cpc'] == $b['cpc']) return 0;
	return ($a['cpc'] < $b['cpc']) ? 1 : -1;
}

function uc_cmp_userProfitList_ctr_asc($a, $b)
{
	if ($a['ctr'] == $b['ctr']) return 0;
	return ($a['ctr'] > $b['ctr']) ? 1 : -1;
}
function uc_cmp_userProfitList_ctr_desc($a, $b)
{
	if ($a['ctr'] == $b['ctr']) return 0;
	return ($a['ctr'] < $b['ctr']) ? 1 : -1;
}

function uc_cmp_userProfitList_cvr_asc($a, $b)
{
	if ($a['cvr'] == $b['cvr']) return 0;
	return ($a['cvr'] > $b['cvr']) ? 1 : -1;
}
function uc_cmp_userProfitList_cvr_desc($a, $b)
{
	if ($a['cvr'] == $b['cvr']) return 0;
	return ($a['cvr'] < $b['cvr']) ? 1 : -1;
}

function uc_cmp_userProfitList_cost_asc($a, $b)
{
	if ($a['cost'] == $b['cost']) return 0;
	return ($a['cost'] > $b['cost']) ? 1 : -1;
}
function uc_cmp_userProfitList_cost_desc($a, $b)
{
	if ($a['cost'] == $b['cost']) return 0;
	return ($a['cost'] < $b['cost']) ? 1 : -1;
}

function uc_cmp_userProfitList_sales_asc($a, $b)
{
	if ($a['sales'] == $b['sales']) return 0;
	return ($a['sales'] > $b['sales']) ? 1 : -1;
}
function uc_cmp_userProfitList_sales_desc($a, $b)
{
	if ($a['sales'] == $b['sales']) return 0;
	return ($a['sales'] < $b['sales']) ? 1 : -1;
}

function uc_cmp_userProfitList_roi_asc($a, $b)
{
	if ($a['roi'] == $b['roi']) return 0;
	return ($a['roi'] > $b['roi']) ? 1 : -1;
}
function uc_cmp_userProfitList_roi_desc($a, $b)
{
	if ($a['roi'] == $b['roi']) return 0;
	return ($a['roi'] < $b['roi']) ? 1 : -1;
}

function uc_cmp_userProfitList_balance_asc($a, $b)
{
	if ($a['balance'] == $b['balance']) return 0;
	return ($a['balance'] > $b['balance']) ? 1 : -1;
}
function uc_cmp_userProfitList_balance_desc($a, $b)
{
	if ($a['balance'] == $b['balance']) return 0;
	return ($a['balance'] < $b['balance']) ? 1 : -1;
}

function quickSort(array $array, $operation, $orderType = 'desc') {
    $length = count($array);
    $left_array = array();
    $right_array = array();
    if($length <= 1){
        return $array;
    }
    
    $key = $array[0];
    //注意这里的i一定要等于1，也就是从数组的第二个值开始比较，因为第一个值已经是被选定为对比值了
    if($orderType == 'desc') {
	    for($i = 1; $i < $length; $i++) {
	        if($array[$i][$operation] < $key[$operation]){
	            $right_array[] = $array[$i];
	        } else {
	            $left_array[] = $array[$i];
	        }
	    }
	} else {
		for($i = 1; $i < $length; $i++) {
	        if($array[$i][$operation] > $key[$operation]){
	            $right_array[] = $array[$i];
	        } else {
	            $left_array[] = $array[$i];
	        }
	    }
	}
    
    $left_array = quickSort($left_array, $operation, $orderType);
    $right_array = quickSort($right_array, $operation, $orderType);
    return array_merge($left_array, array($key), $right_array);    
}

/**
 * 从给定的链接下载文件并保存到本地
 * 
 * @param string $file	保存到本地的文件路径
 * @param string $downloadUrl	网络地址
 */
function download_file($file, $downloadUrl) {
	$fh = fopen($file, 'w');
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $downloadUrl);
	curl_setopt($ch, CURLOPT_FILE, $fh);
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // this will follow redirects
	curl_exec($ch);
	curl_close($ch);
	fclose($fh);
}

/**
 * Debug
 * @param Any $o
 */
function dbg($o, $label) {
	if($label)
		echo "---- $label ----<br/>" . PHP_EOL;
	echo json_encode($o) . ' <br/>' . PHP_EOL;
}

/**
 * 缓存某个数据直到<strong>北京时间</strong>明天给定点钟.
 * 
 * @param string $key Cache key.
 * @param mixed $val Whatever value.
 * @param float $hour = 8 默认缓存到<strong>北京时间</strong>明天早上8:00. 可以个小数. 例如 7.5表示到明天早上7:30. 
 */
function cache_till($key, $val, $hour = 8) {
	S($key, $val, 86400 - time() % 86400 + $hour * 3600);
}
/**
 * 计算一个中英文混合字符串所包含的bytes。一个中文算2个bytes，一个英文算1个byte。
 * @param string $str
 * @return int bytes.
 */
function zh_strlen($str) {
	return (strlen($str) + mb_strlen($str, 'UTF-8')) / 2;
}
/**
 * 查找子串，从位置0开始，直至给定bytes。一个中文算2个bytes，一个英文算1个byte。。
 * @param string $str
 * @param int $bytes
 */
function zh_substr($str, $bytes) {
	if(zh_strlen($str) <= $bytes) {
		return $str;
	} else {
		$substr = $str;
		while(zh_strlen($substr) > $bytes) { // 每次删掉一个字，直至符合长度要求
			$substr = mb_substr($substr, 0, mb_strlen($substr, 'UTF-8') - 1, 'UTF-8');
		}
		return $substr;
	}
}
/**
 * 将带中英文字符串中的英文转为小写。
 * @param string $str
 * @return string
 */
function zh_strtolower($str) {
	if(is_array($str)) // DEBUG TODO remove this!
		throw_exception('参数必须是字符串');
	return mb_strtolower($str, 'UTF-8');
}
/**
 * 将给定的数组中的每个元素都转化为小写。
 * @param array(string) $arr
 * @return array(string) 如果给定的为null或空数组，返回本身（也就是null返回null，空数组返回空数组）。
 */
function zh_arrtolower($arr) {
	if($arr) {
		$res = array();
		foreach($arr as $str) 
			$res[] = zh_strtolower($str);
		return $res;
	} else {
		return $arr;
	}
}
/**
 * 将一个二维数组中的一个字段转化为小写。<strong>注意： 这个函数会更改参数原值，因此没有返回！</strong>
 * @param array2d $arr2d array( array(k=>v) )
 * @param string $col 字段名
 * @param 数组元素是否为object。
 * @return void
 */
function zh_arr2dtolower(&$arr2d, $col, $isEleObj = false) {
	if($arr2d) {
		if(!$isEleObj) {
			foreach($arr2d as &$subarr)
				$subarr[$col] = zh_strtolower($subarr[$col]);
		} else {
			foreach($arr2d as &$subarr)
				$subarr->$col = zh_strtolower($subarr->$col);
		}
	}
}

/**
 * 去除字符串中的所有空字符。
 * @param string $str
 * @return string|null 如果给定字符串为null，则返回null；否则返回去除空字符串后的剩余部分。
 */
function trim_all($str) {
	return $str ? preg_replace('/\s+/', '', $str) : $str;
}

class NewzanException extends ThinkException {
}


/**
 * 参数返回常量。
 */
class RetStatus {
	/** @var int Return status: not found */
	const NOT_FOUND = 404;
	const NOT_SERVER = 301;
	const ACCESS_DENY = 10;
	/**@var 无店铺 */
	const NO_SHOP_DENY = 11;
	/**@var 未开通直通车 */
	const NO_ZTC_DENY = 12;
	
    const PARAM_ERR = 100;
    const OK = 200;
    const INTER_ERR = 500;
    const LOGIC_ERR = 110;
    /** @var int Return status: inner error */
    const INNER_ERR = 500;
    /** @var int TAOBAO API error */
    const TOP_API_ERR = 600;
    /** @var int Return status: login/auth required */
    const AUTH_REQUIRED = 401;
 
}

class ParamsCheckUtils {
	public static function checkNotNull($value, $msg = '') {
		$msg = $msg ? $msg : '参数不能为空';
		if(self::checkEmpty($value)){
			throw new NewzanException( $msg, RetStatus::PARAM_ERR);
		}

	}

	public static function checkMaxLength($value, $maxLength, $msg = '', $countBytes = false){
		$msg = $msg ? $msg : '参数不能超过' . $maxLength . '个字符';
		if(!self::checkEmpty($value) && (
				(!$countBytes && mb_strlen($value , "UTF-8") > $maxLength))
				|| ($countBytes && zh_strlen($value) > $maxLength * 2)
		){
			throw new NewzanException( $msg, RetStatus::PARAM_ERR);
		}
	}

	public static function checkMaxValue($value,$maxValue,$msg = ''){
		$msg = $msg ? $msg : '参数最大值不能大于' . $maxValue;
		if(self::checkEmpty($value)){
			throw new NewzanException( '参数不能为空', RetStatus::PARAM_ERR);
		}
		self::checkNumeric($value);
		if($value > $maxValue){
			throw new NewzanException( $msg, RetStatus::PARAM_ERR);
		}
	}

	public static function checkMinValue($value, $minValue, $msg = '') {
		$msg = $msg ? $msg : '参数最大值不能小于' . $minValue;
		if(self::checkEmpty($value)){
			throw new NewzanException( '参数不能为空', RetStatus::PARAM_ERR);
		}
		self::checkNumeric($value);
		if($value < $minValue){
			throw new NewzanException( $msg, RetStatus::PARAM_ERR);
		}
	}

	public static function checkNumeric($value,$msg = '') {
		$msg = $msg ? $msg : '参数必须为数值';
		if(!is_numeric($value))
			throw new NewzanException( $msg, RetStatus::PARAM_ERR);
	}

	public static function checkEmpty($value) {
		if(!isset($value))
			return true ;
		if($value === null )
			return true;
		if(trim($value) === "")
			return true;
		return false;
	}

	/**
	 * 检查是否为空
	 * mixed $value  被检查值
	 * void
	 * Exception NewzanException
	 */
	public static function checkNULL( $value , $msg = '' ){
		$msg = $msg ? $msg : '数据不能为空';
		$flag = false;
		if(!isset($value))
			$flag = true ;
		if($value === null )
			$flag = true;
		if(trim($value) === "")
			$flag = true;
		if( ! count( $value) ){
			$flag = true;
		}
		if( $flag ){
			throw new NewzanException( $msg, RetStatus::PARAM_ERR);
		}
		return false;
	}


	public static function checkDate($value , $msg = ''){
		$msg = $msg ? $msg : '日期格式错误';
		$timestamp = strtotime($value);
		if(!$timestamp){
			throw new NewzanException( $msg, RetStatus::PARAM_ERR);
		}
	}

	public static function isLegal($value , $msg){
		// using php filter_input
	}
}

function cus_array_map($data, $filter)
{
	
	if(is_array($data)) {
		foreach ($data as $key => $value) {
			$data[$key] = cus_array_map($value, $filter);
		}
	} else {
		$data = $filter($data);
		return $data;
	}
}

/**
 * 获取输入参数 支持过滤和默认值
 * 使用方法:
 * <code>
 * I('id',0); 获取id参数 自动判断get或者post
 * I('post.name','','htmlspecialchars'); 获取$_POST['name']
 * I('get.'); 获取$_GET
 * </code>
 * @param string $name 变量的名称 支持指定类型
 * @param mixed $default 不存在的时候默认值
 * @param mixed $filter 参数过滤方法
 * @return mixed
 */
function I($name,$default='',$filter=null,$datas=null) {
	static $_PUT	=	null;
	if(strpos($name,'/')){ // 指定修饰符
		list($name,$type) 	=	explode('/',$name,2);
	}elseif(C('VAR_AUTO_STRING')){ // 默认强制转换为字符串
        $type   =   's';
    }
    if(strpos($name,'.')) { // 指定参数来源
        list($method,$name) =   explode('.',$name,2);
    }else{ // 默认为自动判断
        $method =   'param';
    }
    switch(strtolower($method)) {
        case 'get'     :   
        	$input =& $_GET;
        	break;
        case 'post'    :   
        	$input =& $_POST;
        	break;
        case 'put'     :   
        	if(is_null($_PUT)){
            	parse_str(file_get_contents('php://input'), $_PUT);
        	}
        	$input 	=	$_PUT;        
        	break;
        case 'param'   :
            switch($_SERVER['REQUEST_METHOD']) {
                case 'POST':
                    $input  =  $_POST;
                    break;
                case 'PUT':
                	if(is_null($_PUT)){
                    	parse_str(file_get_contents('php://input'), $_PUT);
                	}
                	$input 	=	$_PUT;
                    break;
                default:
                    $input  =  $_GET;
            }
            break;
        case 'path'    :   
            $input  =   array();
            if(!empty($_SERVER['PATH_INFO'])){
                $depr   =   C('URL_PATHINFO_DEPR');
                $input  =   explode($depr,trim($_SERVER['PATH_INFO'],$depr));            
            }
            break;
        case 'request' :   
        	$input =& $_REQUEST;   
        	break;
        case 'session' :   
        	$input =& $_SESSION;   
        	break;
        case 'cookie'  :   
        	$input =& $_COOKIE;    
        	break;
        case 'server'  :   
        	$input =& $_SERVER;    
        	break;
        case 'globals' :   
        	$input =& $GLOBALS;    
        	break;
        case 'data'    :   
        	$input =& $datas;      
        	break;
        default:
            return null;
    }
    if(''==$name) { // 获取全部变量
        $data       =   $input;
        $filters    =   isset($filter)?$filter:C('DEFAULT_FILTER');
        if($filters) {
            if(is_string($filters)){
                $filters    =   explode(',',$filters);
            }
            foreach($filters as $filter){
                // $data   =   array_map($filter,$data); // 参数过滤
                cus_array_map($data, $filter);
            }
        }
    }elseif(isset($input[$name])) { // 取值操作
        $data       =   $input[$name];
        $filters    =   isset($filter)?$filter:C('DEFAULT_FILTER');
        if($filters) {
            if(is_string($filters)){
                if(0 === strpos($filters,'/')){
                    if(1 !== preg_match($filters,(string)$data)){
                        // 支持正则验证
                        return   isset($default) ? $default : null;
                    }
                }else{
                    $filters    =   explode(',',$filters);                    
                }
            }elseif(is_int($filters)){
                $filters    =   array($filters);
            }
            
            if(is_array($filters)){
                foreach($filters as $filter){
                    if(function_exists($filter)) {
                        // $data   =   is_array($data) ? array_map($filter,$data) : $filter($data); // 参数过滤
                        cus_array_map($data, $filter);
                    }else{
                        $data   =   filter_var($data,is_int($filter) ? $filter : filter_id($filter));
                        if(false === $data) {
                            return   isset($default) ? $default : null;
                        }
                    }
                }
            }
        }
        if(!empty($type)){
        	switch(strtolower($type)){
        		case 'a':	// 数组
        			$data 	=	(array)$data;
        			break;
        		case 'd':	// 数字
        			$data 	=	(int)$data;
        			break;
        		case 'f':	// 浮点
        			$data 	=	(float)$data;
        			break;
        		case 'b':	// 布尔
        			$data 	=	(boolean)$data;
        			break;
                case 's':   // 字符串
                default:
                    $data   =   (string)$data;
        	}
        }
    }else{ // 变量默认值
        $data       =    isset($default)?$default:null;
    }
    is_array($data) && array_walk_recursive($data,'think_filter');
    return $data;
}

function getKeywordIndexAvg($keywords)
{
	if(!$keywords) {
		return array();
	}
	$arr_agv = array('impressions','click','ctr','cpc','cvr','avgpos','qscore','wireless_qscore','cost','sales','roi','max_price','cart_total','cart_total_rate','fav_count','fav_count_rate','total_pay_count', 'max_mobile_price');
    foreach ($keywords as $k => $item) {
        foreach ($arr_agv as $a) {
            if(floatval($item[$a]) != 0) {
                $avg[$a][] = $item[$a];
            }
        }
    }
    
    foreach ($arr_agv as $a) {
        $sum = 0;
        foreach ($avg[$a] as $value) {
            $sum += floatval($value);
        }
        $display_avg[$a] = round($sum/count($avg[$a]), 2);
    }

    return $display_avg;
}

function page_html($current_page = 1, $total_items = 0, $page_size = 400)
{
	if($total_items == 0) {
		return '';
	}
	$page_html = '<ul class="items">';
	$up_page = $current_page-1;
	$down_page = $current_page+1;
	if($current_page == 1) {
		$page_html .= '<li class="item prev prev-disabled"><a class="num"><span class="icon"></span></a></li>';
	} else {
		$page_html .= '<li class="item prev"><a class="num" data-page="'.$up_page.'"><span class="icon"></span></a></li>';
	}
	$total_page = ceil($total_items/$page_size);
	if($total_page > 5) {
		if($current_page > 4 && $current_page <= $total_page - 4) {
			for ($i=4; $i > 0 ; $i--) { 
				$page_num = $current_page-$i+1;
				$page_html .= "<li class=\"item\"><a class=\"num";
				if($page_num == $current_page) {
					$page_html .= ' active"';
				} else {
					$page_html .= "\" data-page=\"{$page_num}\"";
				}
				$page_html .= ">{$page_num}</a></li>";
			}
			$page_html .= "<li class=\"item dot\">...</li><li class=\"item\"><a class=\"num\" data-page=".$total_page.">{$total_page}</a></li>";
		} elseif ($current_page > $total_page -4 && $current_page <= $total_page) {
			$page_html .= "<li class=\"item\"><a class=\"num\" data-page=\"1\">1</a></li><li class=\"item dot\">...</li>";
			for ($i=4; $i > 0 ; $i--) { 
				$page_num = $total_page-$i+1;
				$page_html .= "<li class=\"item\"><a class=\"num";
				if($page_num == $current_page) {
					$page_html .= ' active"';
				} else {
					$page_html .= "\" data-page=\"{$page_num}\"";
				}
				$page_html .= ">{$page_num}</a></li>";
			}
		} else {
			for ($i=0; $i < 4; $i++) { 
				$page_num = $i+1;
				$page_html .= "<li class=\"item\"><a class=\"num";
				if($page_num == $current_page) {
					$page_html .= ' active"';
				} else {
					$page_html .= "\" data-page=\"{$page_num}\"";
				}
				$page_html .= ">{$page_num}</a></li>";
			}
			$page_html .= "<li class=\"item dot\">...</li><li class=\"item\"><a class=\"num\" data-page=\"{$total_page}\">{$total_page}</a></li>";
		}
	} else {
		for ($i=0; $i < $total_page; $i++) { 
			$page_num = $i+1;
			$page_html .= "<li class=\"item\"><a class=\"num";
			if($page_num == $current_page) {
				$page_html .= ' active"';
			} else {
				$page_html .= "\" data-page=\"{$page_num}\"";
			}
			$page_html .= ">{$page_num}</a></li>";
		}
	}
	if($current_page == $total_page) {
		$page_html .= '<li class="item next next-disabled"><a class="num"><span class="icon"></span></a></li>';
	} else {
		$page_html .= '<li class="item next"><a class="num" data-page="'.$down_page.'"><span class="icon"></span></a></li>';
	}
	$page_html .= "</ul><div class=\"total\">共 {$total_page} 页，</div><div class=\"form\"><span class=\"text\">到第</span><input class=\"input\" type=\"number\" value=\"1\" min=\"1\" max=\"{$total_page}\"><span class=\"text\">页</span><span class=\"button to_page\">确定</span></div>";
	return $page_html;
}

/**
 * Encryption/Decrypt function
 * @param  string  $string    Encryption/Decrypt source (express/ciphertext)
 * @param  string  $operation Operation type (DECODE、ENCODE)
 * @param  string  $key       The secret key (Default 'Shelpe@001')
 * @param  integer $expiry    Deadline
 * @return string             Express/Ciphertext
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
	$ckey_length = 4;
	$key = md5($key != '' ? $key : 'Shelpe@001');
	// $key = md5($key != '' ? $key : getglobal('authkey'));
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
			return '';
		}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

function autoCondition($y)
{
	switch ($y) {
		case 2:
			$o = '=';
			break;
		case 3:
			$o = '<';
			break;
		case 4:
			$o = '<=';
			break;
		case 5:
			$o = '>=';
			break;
		case 1:
		default:
			$o = '>';
			break;
	}
	return $o;
}

/**
 * 我的思路我牛逼解析数据
 * @param  string  $thinkingContent  思路serialize后的数据
 * @return string  $y                思路中文化
 */
function analyticalThinking($thinkingContent)
{
	$indexName = array(
			'impressions' => '展现量',
			'click' => '点击量',
			'ctr' => '点击率',
			'cpc' => '平均点击花费',
			'cvr' => '点击转化率',
			'avgpos' => '宝贝排名',
			'qscore' => '计算机质量得分',
			'wirelessQscore' => '移动质量得分',
			'cost' => '总花费',
			'sales' => '总成交',
			'roi' => '投入产出比',
			'fav_count' => '收藏数',
			'fav_count_rate' => '收藏率',
			'cart_total' => '购物车数',
			'cart_total_rate' => '购物车率',
			'total_pay_count' => '总成交笔数'
		);
	$conditionName = array(
			'>' => '大于',
			'>=' => '大于等于',
			'<' => '小于',
			'<=' => '小于等于',
			'=' => '等于',
		);
	$y = '';
	$thinkingContent = unserialize($thinkingContent);
	if($thinkingContent) {
		// 条件
		$num = count($thinkingContent['indexs'])-1;
		foreach ($thinkingContent['indexs'] as $key => $think) {
			$y .= "<div class=\"filter_box\">";
			foreach ($think as $index_key => $index_value) {
				$y .= "<div>{$indexName[$index_value['intdex_name']]} {$conditionName[$index_value['intdex_condition']]}<span class=\"red\">{$index_value['intdex_value']}</span>倍的宝贝";
				switch ($index_value['intdex_srouceType']) {
					case 1:
						$y .= '均值';
						break;
					case 2:
						$y .= '最大值';
						break;
					case 4:
						$y .= '行业均值';
						break;
					case 3:
					default:
						$y .= '自定义'.$index_value['intdex_srouceValue'];
						break;
				}
				if($index_value['intdex_srouceType'] == 3 && in_array($index_value['intdex_name'], array('ctr','cvr','fav_count_rate','cart_total_rate'))) {
					$y .= '%';
				} elseif ($index_value['intdex_srouceType'] == 3 && in_array($index_value['intdex_name'], array('cpc','cost','sales'))) {
					$y .= '元';
				}
				$y .='</div>';
			}
			$y .= "</div>";
			if($key != $num) {
				$y .= "<div>或者</div>";
			}
		}
		// 时效
		switch ($thinkingContent['date']) {
			case '1':
				$y .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">昨天</span></div>";
				break;
			case '3':
				$y .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近三天</span></div>";
				break;
			case '7':
				$y .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近一周</span></div>";
				break;
			case '15':
				$y .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近半个月</span></div>";
				break;
			case '30':
				$y .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近一个月</span></div>";
				break;
			case '90':
				$y .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近三个月</span></div>";
				break;
			default:
				$y .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">自定义最近{$thinkingContent['date']}天</span></div>";
				break;
		}
		if((int)$thinkingContent['delete']['status'] === 1) {
			$y .= "<div style=\"margin-top:10px;\">删除关键词</div>";
		}

		if($thinkingContent['priceModel']['status'] == 1) {
			if($thinkingContent['priceModel']['priceType'] == 1) {
				$y .= "<div style=\"margin-top:10px;\">按百分比";
				$y .= $thinkingContent['priceModel']['optionType'] == 1 ? '降价'.$thinkingContent['priceModel']['priceValue']*100 . '%' . ",最低不能少于{$thinkingContent['priceModel']['priceExtreme']}元" : '提价'.$thinkingContent['priceModel']['priceValue']*100 . '%' . ",最高不能多于{$thinkingContent['priceModel']['priceExtreme']}元";
				$y .= "</div>";
			} else if ($thinkingContent['priceModel']['priceType'] == 2) {
				$y .= "<div style=\"margin-top:10px;\">原基础上";
				$y .= $thinkingContent['priceModel']['optionType'] == 1 ? '降价'.$thinkingContent['priceModel']['priceValue'] .'元' . ",最低不能少于{$thinkingContent['priceModel']['priceExtreme']}元" : '提价'.$thinkingContent['priceModel']['priceValue'] . '元' . ",最高不能多于{$thinkingContent['priceModel']['priceExtreme']}元";
				$y .= "</div>";
			} else {
				$y .= "<div style=\"margin-top:10px;\">统一出价：{$thinkingContent['priceModel']['priceValue']}元</div>";
			}
		}
		// 操作-匹配模式
		if($thinkingContent['matchscopeModel']['status'] === 1) {
			$y .= "<div style=\"margin-top:10px;\">匹配模式：";
			switch ($thinkingContent['matchscopeModel']['value']) {
				case '1':
					$y .= '广泛匹配';
					break;
				case '2':
					$y .= '中心词';
					break;
				case '3':
					$y .= '精确匹配';
					break;
			}
			$y .="</div>";
		}
	}
	return $y;
}

function siluFilters($filters, $other = false)
{
	$filters_string = "";
	if($filters) {
		$indexName = array(
			'impressions' => '展现量',
			'click' => '点击量',
			'ctr' => '点击率',
			'cpc' => '平均点击花费',
			'cvr' => '点击转化率',
			'avgpos' => '宝贝排名',
			'qscore' => '计算机质量得分',
			'wirelessQscore' => '移动质量得分',
			'cost' => '总花费',
			'sales' => '总成交',
			'roi' => '投入产出比',
			'fav_count' => '收藏数',
			'fav_count_rate' => '收藏率',
			'cart_total' => '购物车数',
			'cart_total_rate' => '购物车率',
			'total_pay_count' => '总成交笔数'
		);
		$num = count($filters)-1;
		foreach ($filters as $key => $item) {
			$num_item = count($item);
			$cou = 0;
			if($num_item > 1)
				$filters_string .= '(';
			foreach ($item as $index_key => $index_value) {
				$cou++;
				if(isset($index_value['min']['value']) && isset($index_value['max']['value'])) {
					$filters_string .= $index_value['min']['value'] . '<' .  ((isset($index_value['min']['eq']) && $index_value['min']['eq']) ? '=' : '') . $indexName[$index_key] . '<' .  ((isset($index_value['max']['eq']) && $index_value['max']['eq']) ? '=' : '') . $index_value['max']['value'];
				} else if(isset($index_value['min'])) {
					$filters_string .= $indexName[$index_key] . '>' .  ((isset($index_value['min']['eq']) && $index_value['min']['eq']) ? '=' : '') . $index_value['min']['value'];
				} else if(isset($index_value['max'])) {
					$filters_string .= $indexName[$index_key] . '<' .  ((isset($index_value['max']['eq']) && $index_value['max']['eq']) ? '=' : '') . $index_value['max']['value'];
				}
				$filters_string .= ($cou == $num_item) ? '' : ' 并且 ';
			}
			if($num_item > 1)
				$filters_string .= ')';
			$filters_string .= ($key == $num) ? '' : ' 或者 ';
		}
	}

	if($other) {
		$thinkingContent = unserialize($other);

		// 时效
		switch ($thinkingContent['date']) {
			case '1':
				$filters_string .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">昨天</span></div>";
				break;
			case '3':
				$filters_string .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近三天</span></div>";
				break;
			case '7':
				$filters_string .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近一周</span></div>";
				break;
			case '15':
				$filters_string .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近半个月</span></div>";
				break;
			case '30':
				$filters_string .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近一个月</span></div>";
				break;
			case '90':
				$filters_string .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">最近三个月</span></div>";
				break;
			default:
				$filters_string .= "<div style=\"margin-top:10px;\">参考数值时效：<span class=\"red\">自定义最近{$thinkingContent['date']}天</span></div>";
				break;
		}
		// 操作-调价
		if((int)$thinkingContent['delete']['status'] === 1) {
			$filters_string .= "<div style=\"margin-top:10px;\">删除关键词</div>";
		}

		if($thinkingContent['priceModel']['status'] == 1) {
			if($thinkingContent['priceModel']['priceType'] == 1) {
				$filters_string .= "<div style=\"margin-top:10px;\">按百分比";
				$filters_string .= $thinkingContent['priceModel']['optionType'] == 1 ? '降价'.$thinkingContent['priceModel']['priceValue']*100 . '%' . ",最低不能少于{$thinkingContent['priceModel']['priceExtreme']}元" : '提价'.$thinkingContent['priceModel']['priceValue']*100 . '%' . ",最高不能多于{$thinkingContent['priceModel']['priceExtreme']}元";
				$filters_string .= "</div>";
			} else if ($thinkingContent['priceModel']['priceType'] == 2) {
				$filters_string .= "<div style=\"margin-top:10px;\">原基础上";
				$filters_string .= $thinkingContent['priceModel']['optionType'] == 1 ? '降价'.$thinkingContent['priceModel']['priceValue'] .'元' . ",最低不能少于{$thinkingContent['priceModel']['priceExtreme']}元" : '提价'.$thinkingContent['priceModel']['priceValue'] . '元' . ",最高不能多于{$thinkingContent['priceModel']['priceExtreme']}元";
				$filters_string .= "</div>";
			} else {
				$filters_string .= "<div style=\"margin-top:10px;\">统一出价：{$thinkingContent['priceModel']['priceValue']}元</div>";
			}
		}
		// 操作-匹配模式
		if($thinkingContent['matchscopeModel']['status'] === 1) {
			$filters_string .= "<div style=\"margin-top:10px;\">匹配模式：";
			switch ($thinkingContent['matchscopeModel']['value']) {
				case '1':
					$filters_string .= '广泛匹配';
					break;
				case '2':
					$filters_string .= '中心词';
					break;
				case '3':
					$filters_string .= '精确匹配';
					break;
			}
			$filters_string .="</div>";
		}
	}

	return $filters_string;
}

function createObject ($data){
	$html = '';
	if($data) {
		$html .='<table class="metrotable">';
		foreach ($data['items'] as $campaign_id => $campaign) {
			$html .= "<tr><td>{$campaign['base']['title']}</td><td><table>";
			foreach ($campaign['detail'] as $adgroup_id => $adgroup) {
				$html .= "<tr><td><div style=\"width:40px;height:40px;float:left\"><img src=\"{$adgroup['img_url']}\" width=\"34px\" style=\"border:1px solid #d1d1d1; padding:2px;\"></div><div class=\"data\" style=\"display:inline-block;max-width:300px;margin-left:10px;\"><a href=\"#\">{$adgroup['a_title']}</a></div></td></tr>";
			}
			$html .= "</table></td></tr>";
		}
		$html .="</table>";
	}
	return $html;
}

function menuTree($modules = array(), $pid = false)
{
	$p = array();
	$data = array();
	if(!$modules) {
		return $data;
	}
	$num = strlen($pid);
	foreach ($modules as &$module) {
		// continue;
		if(!$pid) {
			$key = substr($module['menu_path'], 0, strlen($module['menu_path']) -2);
			$p[$key][] = $module;
		} elseif (strlen($module['menu_path']) == $num) {
			$p[''][] = $module;
		} else {
			$key = substr($module['menu_path'], 0, $num);
			$p[$key][] = $module;
		}
	}
	$i = 0;
	foreach ($p[''] as $item) {
		$data[$i]['info'] = array(
				'title' => $item['menu_name'], 'url' => $item['menu_url'], 'icon' => $item['menu_icon'], 'path' => $item['menu_path'],'info' => $item['summary']
			);

		if (isset($p[$item['menu_path']])) {
			foreach ($p[$item['menu_path']] as $s) {
				$data[$i]['items'][] = array(
						'title'=>$s['menu_name'],
						'url'=>$s['menu_url'],
						'icon'=>$s['menu_icon'],
						'path' => $s['menu_path'],
						'info' => $s['summary']
					);
			}
		}
		$i++;
	}
	unset($p);
	return $data;
}

function getOptionName($menu = array(), $module = 'Index', $action = 'index')
{
	$module = strtolower($module);
	$action = strtolower($action);

	$res = array(
			'module' => array('url'=>'', 'name'=>''),
			'action' => array('url'=>'', 'name'=>''),
			'subMenu' => array()
		);

	foreach ($menu as $value) {
		$url = explode('/', $value['info']['url']);
		if(strtolower($url[$value['info']['lavel']]) == $module) {
			$res['module']['name'] = $value['info']['name'];
			$res['module']['url'] = U($value['info']['url']);
			foreach ($value['list'] as $m) {
				$url = explode('/', $m['url']);
				if(strtolower($url[$m['lavel']]) == $action) {
					$res['action']['name'] = $m['name'];
					$res['action']['url'] = U($m['url']);
					break;
				}
			}
			$res['subMenu'] = $value['list'];
			break;
		}
	}
	return $res;
}